# This is a sample Python script.
import random
# Press ⌃R to execute it or replace it with your code.
# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.
import pygame

from playwright.sync_api import Playwright, sync_playwright, expect

def configVoice():
    pygame.init()
    pygame.mixer.music.load('tik.mp3')  # 加载MP3文件
    pygame.mixer.music.play()  # 播放MP3文件


def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context(storage_state="auth.json")
    page = context.new_page()
    page.goto(
        "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=北京,BJP&ts=郑州,ZZF&date=2024-04-30&flag=N,Y,Y")
        # "https://kyfw.12306.cn/otn/leftTicket/init?linktypeid=dc&fs=北京,SJP&ts=石家庄,ZZF&date=2023-09-28&flag=N,Y,Y")

    # page.get_by_role("link", name="查询", exact=True).click()
    page.locator("li").filter(has_text="GC-高铁/城际").get_by_label("按空格键进行操作").check()
    page.get_by_label("北京西").check()

    page.get_by_label("显示全部可预订车次,按空格键进行操作").check()
    page.locator("#cc_seat_type_O_check").check()

    page.wait_for_timeout(1000)
    page.get_by_role("link", name="查询", exact=True).click()

    while True:
        wait_time = random.randint(2, 15)
        page.wait_for_timeout(wait_time * 1000)
        page.get_by_role("link", name="查询", exact=True).click()
        page.wait_for_timeout(1000)
        elements = page.query_selector_all('#queryLeftTable tr:not([style*="display:none;"])')
        print(len(elements))
        if len(elements) != 0:
            configVoice()

    # ---------------------
    # context.storage_state(path="auth.json")
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')
    pass

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
